namespace Digitalmes.Application.Sys.Configs.Commands;

/// <summary>
/// 更新系统配置命令。
/// </summary>
/// <param name="Config"></param>
public record UpdateConfigCommand(long Id, SysConfigDto Config) : IRequest<IResult<bool>>;

internal sealed class UpdateConfigCommandHandler(IRepository<SysConfig> repo) : IRequestHandler<UpdateConfigCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateConfigCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Config.Code && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("系统配置已存在");
        }

        var config = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (config == null)
        {
            return Result.Failure("未找到要更新的配置");
        }

        if (config.IsFixed)
        {
            return Result.Failure("配置项为系统内置，不能修改");
        }

        config.Name = request.Config.Name;
        config.Value = request.Config.Value;
        config.IsFixed = request.Config.IsFixed;
        config.Remark = request.Config.Remark;
        config.Status = request.Config.Status;

        var ok = await repo.UpdateAsync(config, m => new
        {
            m.Name,
            m.Value,
            m.IsFixed,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
